package cn.bdqn.witcity.controller;

import cn.bdqn.witcity.entity.Menu;
import cn.bdqn.witcity.entity.Role;
import cn.bdqn.witcity.entity.vo.MenuVo;
import cn.bdqn.witcity.service.MenuService;
import cn.bdqn.witcity.service.RoleService;
import cn.bdqn.witcity.util.ResponseResult;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;

@Controller
public class MenuController {
    @Resource
    MenuService menuService;
    @Resource
    RoleService roleService;

    @RequestMapping("/sys/menuList")
    public String menuMgr(){
        return "/views/user/menu/list";
    }
    @RequestMapping("/sys/menus")
    @ResponseBody
    public ResponseResult menus(MenuVo menuVo, Integer page, Integer limit){
        if(page==null){
            page=1;
        }
        if(limit==null){
            limit=10;
        }
        menuVo.setPage((page-1)*limit);
        menuVo.setLimit(limit);
        int count=menuService.getMenuCount(menuVo);
        List<Menu> menus=menuService.getAllMenuByPage(menuVo);
        return new ResponseResult(0,"",menus,count);
    }
    @RequestMapping("/toUpdateMenu")
    public String toUpdateMenu(Model model){
        Role role=new Role();
        List<Role> roles=roleService.getAllRole(role);
        List<Menu> menus=menuService.getAllParentMenu();
        model.addAttribute("roles",roles);
        model.addAttribute("menus",menus);
        return "/views/user/menu/menuform";

    }
    @RequestMapping("/updateMenu")
    @ResponseBody
    public ResponseResult updateMenu(Integer role,String menus){
        int result=0;
        String[] menusList=menus.split(",");
        for(int i=0;i<menusList.length;i++){
            result+=roleService.addMenuRole(role,Integer.parseInt(menusList[i]));
        }
        return new ResponseResult(200,"",result);
    }
}
